<template>
	<view>
		<web-view v-if="allUrl" :src="allUrl" :update-title='false'></web-view>
	</view>
</template>
<script>
	import {
		mapState
	} from "vuex";
	import {
		Api
	} from "@/utils/Api.js";
	export default {
		data() {
			return {
				// 注意只能放到static目录下面
				// viewerUrl: '/appplication/static/pdf/web/viewer.html',
				viewerUrl: '/static/pdf/web/viewer.html',
				allUrl: '',
				pdfUrl: "",
				title: '',
			}
		},
		onLoad(options) { //需要传入pdf文件的url
			console.log('options', options);
			// let records = JSON.parse(options.record);
			let records = JSON.parse(decodeURIComponent(options.record));			
			console.log('options.record', options.record);
			if (records) {
				uni.setNavigationBarTitle({
					title: records.name
				})
				
				console.log('Api.baseUrl', Api.baseUrl);
				let url = decodeURIComponent(records.url);
				console.log('url', url);
				if (url.indexOf('http') != 0) {
					if (url.indexOf('/') !=0)
						url = '/' + url;
					url = Api.baseUrl + url;
				}
				this.pdfUrl = url;
				console.log('pdfUrl', this.pdfUrl);
				this.title = records.name
				this.loadPdf(this.pdfUrl, records.name)				
			}
		},
		methods: {
			async loadPdf(pdfUrl, title) {
				// #ifdef APP-PLUS
				switch (uni.getSystemInfoSync().platform) {
					case 'android':
						console.log("loadPdf", '运行Android上');
						this.loadPdfOnAndroid(pdfUrl)
						break;
					case 'ios':
						console.log("loadPdf", '运行iOS上');
						this.loadPdfOnIos(pdfUrl)
						break;
					default:
						console.log("loadPdf", '运行在开发者工具上');
						break;
				}
				// #endif
				
				// #ifdef H5
				this.allUrl = this.viewerUrl + '?file=' + encodeURIComponent(pdfUrl);
				
				console.log('H5 allUrl', this.allUrl, 'title', title);
				// this.allUrl = this.viewerUrl;
				uni.setNavigationBarTitle({
					title
				})
				// #endif
				
				// #ifdef MP-WEIXIN
				try {
					const {
						tempFilePath
					} = await uni.downloadFile({
						url: pdfUrl
					});
					
					// switch (uni.getSystemInfoSync().platform) {
					// 	case 'android':
					// 		uni.navigateBack();
					// 		break;
					// 	case 'ios':
					// 		// 苹果不能 navigateBack，会导致打开pdf后，很快又爱回
					// 		break;
					// 	default:
					// 		break;
					// }

					await uni.navigateBack();

					await uni.openDocument({
						filePath: tempFilePath,
						fileType: 'pdf',
						showMenu: true // 显示菜单
					});
				} catch (err) {
					console.error('打开PDF失败:', err);
					uni.showToast({
						title: '打开PDF失败',
						icon: 'none'
					});
				}				
				// #endif
			},
			async loadPdfOnAndroid(pdfUrl) {
				let tempFilePath = await this.downloadPdf(pdfUrl)
				let localFilePath = plus.io.convertLocalFileSystemURL(tempFilePath)
				console.log("downloadFile=======localFilePath", localFilePath)
				this.allUrl = this.viewerUrl + '?file=' + encodeURIComponent(localFilePath)
				console.log("downloadFile=======this.allUrl", this.allUrl)
			},
			async loadPdfOnIos(pdfUrl) {
				let tempFilePath = await this.downloadPdf(pdfUrl)
				uni.openDocument({
					filePath: tempFilePath,
					showMenu: true,
					success: function(res) {
						console.log('打开文档成功');
					}
				});
			},
			downloadPdf(pdfUrl) {
				return new Promise(resolve => {
					uni.downloadFile({
						url: pdfUrl,
						success: (res) => {
							if (res.statusCode === 200) {
								let tempFilePath = res.tempFilePath
								uni.getFileInfo({
									filePath: tempFilePath,
									success: async imgInfo => {
										console.log("downloadPdf=======getFileInfo",
											imgInfo.size);
										if (imgInfo.size) return resolve(tempFilePath)
										else return resolve(await this.downloadPdf(pdfUrl))
									}
								})
							}
						},
						async fail(err) {
							return resolve(await this.downloadPdf(pdfUrl))
						}
					});
				})
			},
			onNavigationBarButtonTap() {
				var url = this.pdfUrl
				var title = ''
				let index = url.lastIndexOf(".")
				let titleTwo = url.lastIndexOf("/")
				title = this.title ? (this.title + url.substring(index, url.length)) : titleTwo
				console.log(title, '////');

				let dtask = plus.downloader.createDownload(url, {
						//本地路径开头使用file://，跟上手机文件本地目录storage/emulated/0，就是用户文件管理器能看到的了，之后我创建微垠作为文件夹，后缀是用于文件命名和格式修改，大家可以使用变量。
						filename: "file://storage/emulated/0/mdej/" + title //利用保存路径，实现下载文件的重命名
					},
					function(d, status) {
						//d为下载的文件对象
						if (status == 200) {
							//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
							let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
							plus.runtime.openFile(d.filename); //选择软件打开文件
							uni.showToast({
								title: '文件保存路径' + d.filename,
								icon: 'none',
								duration: 6000,
							})
						} else {
							//下载失败
							plus.downloader.clear(); //清除下载任务
						}
					})
				dtask.start();
			}
		},
		computed: {
			...mapState(["loginInfo"]),
		},
	}
</script>